import { getRequest } from "@/api/request";
import { AxiosResponse } from "axios";

interface Query {
  id: string | number | undefined;
  offset: number;
  limit: number;
  type: string | number | undefined;
}

const REQUEST_URL = {
  commentList: "/comment/music",
  hotCommentList: "/comment/hot",
  newCommentList: "/comment/new",
};

const handleComment = (res: AxiosResponse) => {
  if (res.data.comments) {
    const commentList = res.data.comments.map((it) => {
      return {
        commentId: it.commentId,
        userImg: it.user.avatarUrl,
        userName: it.user.nickname,
        date: it.timeStr,
        likeNum: it.likedCount,
        content: it.content,
        repliesNum: it.beReplied.length,
      };
    });
    return {
      commentList,
      total: res.data.total,
    };
  } else {
    return {
      commentList: [],
      total: 0,
    };
  }
};

const handleHotComment = (res: AxiosResponse) => {
  if (res.data.hotComments) {
    const hotCommentList = res.data.hotComments.map((it) => {
      return {
        commentId: it.commentId,
        userImg: it.user.avatarUrl,
        userName: it.user.nickname,
        date: it.timeStr,
        likeNum: it.likedCount,
        content: it.content,
        repliesNum: it.beReplied.length,
      };
    });

    return {
      hotCommentList,
      total: res.data.total,
    };
  } else {
    return {
      hotCommentList: [],
      total: 0,
    };
  }
};

const handleNewComment = (res: AxiosResponse) => {
  console.log(res, 123);
  if (res.data.hotComments) {
    const hotCommentList = res.data.hotComments.map((it) => {
      return {
        commentId: it.commentId,
        userImg: it.user.avatarUrl,
        userName: it.user.nickname,
        date: it.timeStr,
        likeNum: it.likedCount,
        content: it.content,
        repliesNum: it.beReplied.length,
      };
    });

    return {
      hotCommentList,
      total: res.data.total,
    };
  } else {
    return {
      hotCommentList: [],
      total: 0,
    };
  }
};

export const getCommentList = (query: Query) => {
  return getRequest(
    REQUEST_URL.commentList +
      `?id=${query.id}&limit=${query.limit}&offset=${query.offset}`
  ).then(handleComment);
};

export const getHotCommentList = (query: Query) => {
  return getRequest(
    REQUEST_URL.hotCommentList +
      `?id=${query.id}&limit=${query.limit}&offset=${query.offset}&type=${query.type}`
  ).then(handleHotComment);
};

export const getNewCommentList = (query: Query) => {
  return getRequest(
    REQUEST_URL.newCommentList +
      `?type=0&id=${query.id}&sortType=2&cursor=&pageSize=${query.limit}&pageNo=1`
  ).then(handleNewComment);
};
